<script setup lang="ts">
import { columns, searchFormSchema } from './role.data'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { roleApi } from '@/api/sys/roleApi'
import { IconEnum } from '@/enums/appEnum'
import { useModal } from '@/components/Modal'
import RoleModal from '@/views/sys/role/RoleModal.vue'
import type { RoleDeleteReq } from '@/model/sys/roleModel'
import RoleModuleScopeModal from '@/views/sys/role/RoleModuleScopeModal.vue'
import { RoleComponentCodes } from '@/enums/componentCodesEnum'

defineOptions({ name: 'RoleList' })
const [registerModal, { openModal }] = useModal()
const [registerModuleScopeModal, { openModal: openModuleScopeModal }] = useModal()
const [registerTable, { reload }] = useTable({
  title: '角色列表',
  api: roleApi.list,
  columns,
  formConfig: { labelWidth: 120, schemas: searchFormSchema },
  useSearchForm: true,
  showTableSetting: true,
  showIndexColumn: false,
  actionColumn: {
    width: 140,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
})

function handleAdd() {
  openModal(true, { isUpdate: false })
}
function handleUpdate(record: Recordable) {
  openModal(true, { record, isUpdate: true })
}
async function handleDelete(record: Recordable) {
  await roleApi.delete(record as RoleDeleteReq)
  reload()
}
function handleModuleScope(record: Recordable) {
  openModuleScopeModal(true, { record })
}
</script>

<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button v-permission="RoleComponentCodes.Add" type="primary" :pre-icon="IconEnum.ADD" @click="handleAdd">
          新增
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: IconEnum.EDIT,
                label: '更新',
                permission: RoleComponentCodes.Update,
                onClick: handleUpdate.bind(null, record),
              },
            ]"
            :drop-down-actions="[
              {
                icon: IconEnum.EDIT,
                label: '功能权限',
                permission: RoleComponentCodes.AssignModules,
                onClick: handleModuleScope.bind(null, record),
              },
              {
                icon: IconEnum.DELETE,
                danger: true,
                label: '删除',
                permission: RoleComponentCodes.Delete,
                popConfirm: {
                  title: '确定?',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <RoleModal @register="registerModal" @success="reload()" />
    <RoleModuleScopeModal @register="registerModuleScopeModal" @success="reload()" />
  </div>
</template>
